package com.xc.hotelmgr.order.modules.ctrip.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xc.hotelmgr.order.common.utils.*;
import com.xc.hotelmgr.order.modules.ali.to.bookrq.request.BookRQ;
import com.xc.hotelmgr.order.modules.ali.to.bookrq.request.OrderGuest;
import com.xc.hotelmgr.order.modules.ali.to.bookrq.response.BookRQResult;
import com.xc.hotelmgr.order.modules.ali.to.cancelrq.CancelRQResult;
import com.xc.hotelmgr.order.modules.ali.to.manuorder.Dailyroom;
import com.xc.hotelmgr.order.modules.ali.to.manuorder.ManuBookRQ;
import com.xc.hotelmgr.order.modules.ctrip.to.cancel.request.CancelRequest;
import com.xc.hotelmgr.order.modules.ctrip.to.commitorder.request.*;
import com.xc.hotelmgr.order.modules.ctrip.to.commitorder.response.CommitOrderResult;
import com.xc.hotelmgr.order.modules.ctrip.to.common.UniqueID;
import com.xc.hotelmgr.order.modules.ctrip.to.saveorder.request.*;
import com.xc.hotelmgr.order.modules.ctrip.to.saveorder.response.SaveOrderResult;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripInterface;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripClient;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripDtInfo;
import com.xc.hotelmgr.order.modules.order.entity.DailyroomEntity;
import com.xc.hotelmgr.order.modules.order.entity.DtOrderChannelsEntity;
import com.xc.hotelmgr.order.modules.order.entity.OrderEntity;
import com.xc.hotelmgr.order.modules.order.service.DailyroomService;
import com.xc.hotelmgr.order.modules.order.service.DtOrderChannelsService;
import com.xc.hotelmgr.order.modules.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("ctripOrderService")
public class CtripOrderService {
    @Autowired
    private DtOrderChannelsService dtOrderChannelsService;

    @Autowired
    private DailyroomService dailyroomService;

    @Autowired
    private OrderService orderService;

    /**
     * 订单保存（2b0c7e0eebe2467a97be3d284313a129）
     *
     * @param bookRQ
     * @return
     */
    public String ctripOrder(BookRQ bookRQ, Long ordId) {
        //查询渠道接口信息
        String userName = bookRQ.getAuthenticationToken().getUsername();
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectKey(Constant.Channel.Ctrip.getValue(), userName);
        CtripDtInfo ctripDtInfo = new CtripDtInfo();
        ctripDtInfo.setAID(Integer.valueOf(dtOrderChannelsEntity.getAccessKey()));
        ctripDtInfo.setSID(dtOrderChannelsEntity.getSid());
        ctripDtInfo.setAccess_Token(dtOrderChannelsEntity.getAccessToken());
        ctripDtInfo.setUniqueID(dtOrderChannelsEntity.getUniqueId());
        ctripDtInfo.setRefresh_Token(dtOrderChannelsEntity.getRefreshToken());
        //构造返回
        BookRQResult bookRQResult = new BookRQResult();
        //更新本地订单
        OrderEntity orderEntity = new OrderEntity();
        R r = saveOrder(bookRQ, ctripDtInfo);
        if (r.getCode() == 0) {
            SaveOrderResult saveOrderResult = (SaveOrderResult) r.get("saveOrderResult");
            Integer buyOrderAmt = Integer.valueOf(r.get("buyOrderPrice").toString());
            orderEntity.setBuyOrderId(saveOrderResult.getHotelReservations().getHotelReservation().getResGlobalInfo().getHotelReservationIDs().get(0).getResID_Value());
            orderEntity.setBuyOrderPrice(buyOrderAmt);
            if (StringUtils.equals(saveOrderResult.getResponseStatus().getAck().toLowerCase(), "success")) {
                R r1 = commitOrder(saveOrderResult, ctripDtInfo);
                if (r1.getCode() == 0) {
                    orderEntity.setBuyStatus(1);
                    bookRQResult.setMessage("创建订单成功");
                    bookRQResult.setResultCode("0");
                } else {
                    orderEntity.setBuyStatus(0);
                    bookRQResult.setMessage("创建订单成功");
                    bookRQResult.setResultCode("0");
                }
            } else {
                orderEntity.setBuyStatus(0);
                bookRQResult.setMessage("创建订单成功");
                bookRQResult.setResultCode("0");
            }
        } else {
            orderEntity.setBuyStatus(0);
            bookRQResult.setMessage("创建订单失败");
            bookRQResult.setResultCode("-9");
        }
        bookRQResult.setOrderId(ordId.toString());
        orderEntity.setId(ordId);
        orderService.updateById(orderEntity);
        return XmlUtils.toXML(bookRQResult);
    }

    /**
     * 保存订单
     *
     * @param bookRQ
     * @param ctripDtInfo
     * @return
     */
    private R saveOrder(BookRQ bookRQ, CtripDtInfo ctripDtInfo) {
        //初始化渠道接口信息
        ctripDtInfo.setICODE(CtripInterface.SaveOrder.getValue());
//        ctripDtInfo.setICODE(CtripInterfaceTest.SubmitOrder.getValue());

        //初始化请求数据
        SaveOrder bookOrder = new SaveOrder();
        //UniqueID
        UniqueID uniqueID = new UniqueID();
        uniqueID.setType("1");
        uniqueID.setID(ctripDtInfo.getUniqueID());
        bookOrder.getUniqueID().add(uniqueID);
        //房间数
        RoomType roomType = new RoomType();
        roomType.setNumberOfUnits(Integer.valueOf(bookRQ.getRoomNum()));
        RoomTypes roomTypes = new RoomTypes();
        roomTypes.setRoomType(roomType);
        RoomStay roomStay = new RoomStay();
        roomStay.setRoomTypes(roomTypes);
        RoomStays roomStays = new RoomStays();
        roomStays.setRoomStay(roomStay);
        HotelReservation hotelReservation = new HotelReservation();
        ResGlobalInfo resGlobalInfo = new ResGlobalInfo();

        hotelReservation.setRoomStays(roomStays);


        //价格计划
        RatePlan ratePlan = new RatePlan();
        ratePlan.setRoomID(bookRQ.getRatePlanCode().replaceAll("-1",""));
//        ratePlan.setRoomID(bookRQ.getRoomTypeId());
//        ratePlan.setRatePlanID(bookRQ.getRatePlanCode());
        RatePlans ratePlans = new RatePlans();
        ratePlans.setRatePlan(ratePlan);
        roomStay.setRatePlans(ratePlans);
        //酒店id
        BasicPropertyInfo basicPropertyInfo = new BasicPropertyInfo();
        basicPropertyInfo.setHotelCode(bookRQ.getHotelId().replaceAll("-1",""));
        roomStay.setBasicPropertyInfo(basicPropertyInfo);

        //入住人信息
        List<PersonName> personNames = Lists.newArrayList();
        PersonName personName = null;
        IDcard iDcard = null;
        for (OrderGuest orderGuest : bookRQ.getOrderGuests()) {
            personName = new PersonName();
            personName.setName(orderGuest.getName());
            if (orderGuest.getIdCode() != null) {
                iDcard = new IDcard();
                if (orderGuest.getIdType() != null) {
                    iDcard.setIDType(orderGuest.getIdType());
                }
                if (orderGuest.getIdCode() != null) {
                    iDcard.setIDNumber(orderGuest.getIdCode());
                }
            }
            personNames.add(personName);
        }
        Customer customer = new Customer();
        customer.setPersonName(personNames);
        Profile profile = new Profile();
        profile.setCustomer(customer);
        ProfileInfo profileInfo = new ProfileInfo();
        profileInfo.setProfile(profile);
        Profiles profiles = new Profiles();
        profiles.setProfileInfo(profileInfo);
        ResGuest resGuest = new ResGuest();
        resGuest.setProfiles(profiles);
        ResGuests resGuests = new ResGuests();
        hotelReservation.setResGlobalInfo(resGlobalInfo);
        resGuests.setResGuest(resGuest);
        hotelReservation.setResGuests(resGuests);
        //联系人
        ContactPerson contactPerson = new ContactPerson();
        PersonName personName1 = new PersonName();
        personName1.setName(bookRQ.getContactName());
        contactPerson.setPersonName(personName1);
        Telephone telephone = new Telephone();
        telephone.setPhoneNumber(bookRQ.getContactTel());
        List<Telephone> tels = Lists.newArrayList();
        tels.add(telephone);
        contactPerson.setTelephone(tels);
        if (StringUtils.isNotBlank(bookRQ.getContactEmail())) {
            contactPerson.setEmail(bookRQ.getContactEmail());
        }
        customer.setContactPerson(contactPerson);
        //最晚抵店时间
        ResGuest_TPA_Extensions resGuest_tpa_extensions = new ResGuest_TPA_Extensions();
        resGuest_tpa_extensions.setLateArrivalTime(bookRQ.getLatestArriveTime());
        resGuest.setTPA_Extensions(resGuest_tpa_extensions);
        resGuest.setArrivalTime(bookRQ.getEarliestArriveTime());
        //总共入住人数
        GuestCount guestCount = new GuestCount();
        guestCount.setCount(Integer.valueOf(bookRQ.getOccupancy()));
        GuestCounts guestCounts = new GuestCounts();
        guestCounts.setGuestCount(guestCount);

        TimeSpan timeSpan = new TimeSpan();
        timeSpan.setStart(bookRQ.getCheckIn());
        timeSpan.setEnd(bookRQ.getCheckOut());


        resGlobalInfo.setGuestCounts(guestCounts);
        resGlobalInfo.setTimeSpan(timeSpan);
        //客人自己自由备注特殊需求
        if (StringUtils.isNotBlank(bookRQ.getComment())) {
            SpecialRequests specialRequests = new SpecialRequests();
            List<SpecialRequests> ss = Lists.newArrayList();
            specialRequests.setText(bookRQ.getComment());
            specialRequests.setName("");
            specialRequests.setParagraphNumber("");
            specialRequests.setRequestCode("");
            specialRequests.setCodeContext("");
            ss.add(specialRequests);
            resGlobalInfo.setSpecialRequests(ss);
        }
        //查询订单总金额
        Integer amt = 0;
        List<DailyroomEntity> dailyroomEntities = dailyroomService.redisSelect(bookRQ.getRatePlanCode(), bookRQ.getCheckIn(), bookRQ.getCheckOut());
        for (DailyroomEntity d : dailyroomEntities) {
            amt += d.getPrice();
        }
        Total total = new Total();
        total.setInclusiveAmount(amt);
        total.setExclusiveAmount(0);
        total.setCurrencyCode("CNY");
        resGlobalInfo.setTotal(total);

        HotelReservations hotelReservations = new HotelReservations();
        hotelReservations.setHotelReservation(hotelReservation);
        bookOrder.setHotelReservations(hotelReservations);
        bookOrder.setTimeStamp(new Date());
        ctripDtInfo.setJsonData(JSONObject.toJSONString(bookOrder));
        try {
            String buyResult = CtripClient.excuteReq(ctripDtInfo);
            log.info("保存订单信息,订单号：{}，返回信息：{}", bookRQ.getTaoBaoOrderId(), buyResult);
            if (buyResult.contains("INVALID_TOKEN")) {
                //如果token失效，休眠2秒钟，再发起
                Thread.sleep(2000);
                return saveOrder(bookRQ, ctripDtInfo);
            }
            log.info("携程保存订单,订单号：{}，返回信息：{}", bookRQ.getTaoBaoOrderId(), buyResult);
            SaveOrderResult saveOrderResult = JSONObject.parseObject(buyResult, SaveOrderResult.class);
            if (saveOrderResult.getErrors().size()>0){
                log.error("保存订单失败，订单号：{}，错误信息：{}", bookRQ.getTaoBaoOrderId(), saveOrderResult.getErrors());
                return R.error(saveOrderResult.getErrors().toString());
            }
            return R.ok().put("saveOrderResult", saveOrderResult).put("buyOrderPrice", amt);
        } catch (Exception ex) {
            log.error("保存订单失败，订单号：{}，错误信息：{}", bookRQ.getTaoBaoOrderId(), ex.toString());
            return R.error();
        }
    }

    /**
     * 半自动创建订单
     *
     * @param bookRQ
     * @param ctripDtInfo
     * @return
     */
    private R manuSaveOrder(ManuBookRQ bookRQ, CtripDtInfo ctripDtInfo) {
        //初始化渠道接口信息
        ctripDtInfo.setICODE(CtripInterface.SaveOrder.getValue());
        //初始化请求数据
        SaveOrder bookOrder = new SaveOrder();
        //UniqueID
        UniqueID uniqueID = new UniqueID();
        uniqueID.setType("1");
        uniqueID.setID(ctripDtInfo.getUniqueID());
        bookOrder.getUniqueID().add(uniqueID);
        //房间数
        RoomType roomType = new RoomType();
        roomType.setNumberOfUnits(Integer.valueOf(bookRQ.getRoomNum()));
        RoomTypes roomTypes = new RoomTypes();
        roomTypes.setRoomType(roomType);
        RoomStay roomStay = new RoomStay();
        roomStay.setRoomTypes(roomTypes);
        RoomStays roomStays = new RoomStays();
        roomStays.setRoomStay(roomStay);
        HotelReservation hotelReservation = new HotelReservation();
        ResGlobalInfo resGlobalInfo = new ResGlobalInfo();
        hotelReservation.setRoomStays(roomStays);


        //价格计划
        RatePlan ratePlan = new RatePlan();
        ratePlan.setRoomID(bookRQ.getRateplanCode().toString().replaceAll("-1",""));
//        ratePlan.setRoomID(bookRQ.getRoomCode().toString());
//        ratePlan.setRatePlanID(bookRQ.getRateplanCode().toString());
        RatePlans ratePlans = new RatePlans();
        ratePlans.setRatePlan(ratePlan);
        roomStay.setRatePlans(ratePlans);
        //酒店id
        BasicPropertyInfo basicPropertyInfo = new BasicPropertyInfo();
        basicPropertyInfo.setHotelCode(bookRQ.getHotelCode().toString().replaceAll("-1",""));
        roomStay.setBasicPropertyInfo(basicPropertyInfo);

        //入住人信息
        List<PersonName> personNames = Lists.newArrayList();
        PersonName personName = null;
        IDcard iDcard = null;
        for (OrderGuest orderGuest : bookRQ.getOrderGuests()) {
            personName = new PersonName();
            personName.setName(orderGuest.getName());
            if (orderGuest.getIdCode() != null) {
                iDcard = new IDcard();
                if (orderGuest.getIdType() != null) {
                    iDcard.setIDType(orderGuest.getIdType());
                }
                if (orderGuest.getIdCode() != null) {
                    iDcard.setIDNumber(orderGuest.getIdCode());
                }
            }
            personNames.add(personName);
        }
        Customer customer = new Customer();
        customer.setPersonName(personNames);
        Profile profile = new Profile();

//        ContactPerson contactPerson =  new ContactPerson();
//        PersonName personName1 = new PersonName();
//        personName1.setName(bookRQ.getName());
//        contactPerson.setPersonName(personName1);
//        Telephone telephone = new Telephone();
//        telephone.setPhoneNumber(bookRQ.getPhone());
//        telephone.setPhoneTechType("5");
//        List<Telephone> telephones = new ArrayList<>();
//        telephones.add(telephone);
//        contactPerson.setTelephone(telephones);
//        contactPerson.setContactType("non");
//

        profile.setCustomer(customer);
        ProfileInfo profileInfo = new ProfileInfo();
        profileInfo.setProfile(profile);
        Profiles profiles = new Profiles();
        profiles.setProfileInfo(profileInfo);
        ResGuest resGuest = new ResGuest();
        resGuest.setProfiles(profiles);
        ResGuests resGuests = new ResGuests();
        hotelReservation.setResGlobalInfo(resGlobalInfo);
        resGuests.setResGuest(resGuest);
        hotelReservation.setResGuests(resGuests);
        //联系人
        ContactPerson contactPerson = new ContactPerson();
        PersonName personName1 = new PersonName();
        personName1.setName(bookRQ.getName());
        contactPerson.setPersonName(personName1);
        Telephone telephone = new Telephone();
        telephone.setPhoneNumber(bookRQ.getPhone());
        List<Telephone> tels = Lists.newArrayList();
        tels.add(telephone);
        contactPerson.setTelephone(tels);
        if (StringUtils.isNotBlank(bookRQ.getEmail())) {
            contactPerson.setEmail(bookRQ.getEmail());
        }
        customer.setContactPerson(contactPerson);
        //最晚抵店时间
        ResGuest_TPA_Extensions resGuest_tpa_extensions = new ResGuest_TPA_Extensions();
        resGuest_tpa_extensions.setLateArrivalTime(DateUtils.format(bookRQ.getLatestTime(), "yyyy-MM-dd HH:mm:ss"));
        resGuest.setTPA_Extensions(resGuest_tpa_extensions);
        resGuest.setArrivalTime(bookRQ.getEarliestTime().toString());
        //总共入住人数
        GuestCount guestCount = new GuestCount();
        guestCount.setCount(Integer.valueOf(bookRQ.getPerNum()));
        GuestCounts guestCounts = new GuestCounts();
        guestCounts.setGuestCount(guestCount);

        TimeSpan timeSpan = new TimeSpan();
        timeSpan.setStart(DateUtils.format(bookRQ.getCheckInDate(), "yyyy-MM-dd"));
        timeSpan.setEnd(DateUtils.format(bookRQ.getCheckOutDate(), "yyyy-MM-dd"));


        resGlobalInfo.setGuestCounts(guestCounts);
        resGlobalInfo.setTimeSpan(timeSpan);
        //客人自己自由备注特殊需求
        if (StringUtils.isNotBlank(bookRQ.getNote())) {
            SpecialRequests specialRequests = new SpecialRequests();
            List<SpecialRequests> ss = Lists.newArrayList();
            specialRequests.setText(bookRQ.getNote());
            specialRequests.setName("");
            specialRequests.setParagraphNumber("");
            specialRequests.setRequestCode("");
            specialRequests.setCodeContext("");
            ss.add(specialRequests);
            resGlobalInfo.setSpecialRequests(ss);
        }
        //查询订单总金额
        Integer amt = 0;

        for (Dailyroom d : bookRQ.getDailyRooms()) {
            amt += d.getPrice();
        }
        Total total = new Total();
        total.setInclusiveAmount(amt);
        total.setExclusiveAmount(0);
        total.setCurrencyCode("CNY");
        resGlobalInfo.setTotal(total);

        HotelReservations hotelReservations = new HotelReservations();
        hotelReservations.setHotelReservation(hotelReservation);
        bookOrder.setHotelReservations(hotelReservations);
        bookOrder.setTimeStamp(new Date());
        ctripDtInfo.setJsonData(JSONObject.toJSONString(bookOrder));
        try {
            String buyResult = CtripClient.excuteReq(ctripDtInfo);
            System.out.println("保存订单信息,订单号：{}，返回信息：{}"+buyResult);
            log.info("保存订单信息,订单号：{}，返回信息：{}", bookRQ.getOrderCode(), buyResult);
            JSONObject buyResultJson = JSONObject.parseObject(buyResult);
            JSONArray Errors=  buyResultJson.getJSONArray("Errors");
            if (Errors.size()!=0){
                return R.error(Errors.toJSONString());
            }
            SaveOrderResult saveOrderResult = JSONObject.parseObject(buyResult, SaveOrderResult.class);
            return R.ok().put("saveOrderResult", saveOrderResult).put("buyOrderPrice", amt);
        } catch (Exception ex) {
            log.error("携程创建订单失败，订单id：{},错误信息：{}", bookRQ.getOrderCode(), ex.toString());
            return R.error();
        }
    }

    /**
     * 提交订单
     *
     * @param saveOrderResult
     * @param ctripDtInfo
     * @return
     */
    private R commitOrder(SaveOrderResult saveOrderResult, CtripDtInfo ctripDtInfo) {
        //初始化渠道信息
        ctripDtInfo.setICODE(CtripInterface.SubmitOrder.getValue());
//        ctripDtInfo.setICODE(CtripInterfaceTest.SubmitOrder.getValue());
        //初始化请求数据
        CommitOrder commitOrder = new CommitOrder();
        ReservationPayment reservationPayment = new ReservationPayment();
        ReservationID reservationID = new ReservationID();
        reservationID.setType("501");
        reservationID.setID(saveOrderResult.getHotelReservations().getHotelReservation().getResGlobalInfo().getHotelReservationIDs().get(0).getResID_Value());
        reservationPayment.setReservationID(reservationID);
        PaymentDetail paymentDetail = new PaymentDetail();
        PaymentAmount paymentAmount = new PaymentAmount();
        paymentAmount.setAmount((int) (saveOrderResult.getHotelReservations().getHotelReservation().getTPA_Extensions().getCost().getAmount()*100));
//        paymentAmount.setAmount(saveOrderResult.getHotelReservations().getHotelReservation().getResGlobalInfo().getTotal().getInclusiveAmount());
        paymentAmount.setCurrencyCode("CNY");
        paymentDetail.setPaymentAmount(paymentAmount);
        paymentDetail.setPaymentType("9");
        paymentDetail.setGuaranteeIndicator(true);
        ChannelAccount channelAccount = new ChannelAccount();
        channelAccount.setChannelAccountIndicator(true);
        paymentDetail.setChannelAccount(channelAccount);
        List<PaymentDetail> paymentDetails = new ArrayList<>();
        paymentDetails.add(paymentDetail);
        reservationPayment.setPaymentDetail(paymentDetails);
        commitOrder.setReservationPayment(reservationPayment);
        ctripDtInfo.setJsonData(JSONObject.toJSONString(commitOrder));
        try {
            String commitResultStr = CtripClient.excuteReq(ctripDtInfo);
            System.out.println("携程订单信息,携程订单号：{}，返回信息：{}"+commitResultStr);
            log.info("携程订单信息,携程订单号：{}，返回信息：{}", reservationID.getID(), commitResultStr);
            if (commitResultStr.contains("INVALID_TOKEN")) {
                return R.error("INVALID_TOKEN");
            }else if (commitResultStr.contains("IP不在支付确认白名单!")){
                return R.error("IP不在支付确认白名单!");
            }
            CommitOrderResult commitOrderResult = JSONObject.parseObject(commitResultStr, CommitOrderResult.class);
            if (StringUtils.equals(commitOrderResult.getResponseStatus().getAck().toLowerCase(), "success")) {
                return R.ok().put("commitOrderResult", saveOrderResult);
            } else {
                log.error("携程提交订单失败，订单号：{}"+commitOrderResult.getErrors().toString(), reservationID.getID());
                return R.error();
            }
        } catch (Exception ex) {
            log.error("commit order error订单号：{},错误信息:{}", reservationID.getID(), ex.toString());
            return R.error();
        }
    }

    /**
     * 取消订单
     *
     * @param orderEntity
     * @param userName
     * @return
     */
    public String cancel(OrderEntity orderEntity, String userName) {
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectKey(Constant.Channel.Ctrip.getValue(), userName);
        CtripDtInfo ctripDtInfo = new CtripDtInfo();
        ctripDtInfo.setAID(Integer.valueOf(dtOrderChannelsEntity.getAccessKey()));
        ctripDtInfo.setSID(dtOrderChannelsEntity.getSid());
        ctripDtInfo.setAccess_Token(dtOrderChannelsEntity.getAccessToken());
        ctripDtInfo.setUniqueID(dtOrderChannelsEntity.getUniqueId());
        ctripDtInfo.setRefresh_Token(dtOrderChannelsEntity.getRefreshToken());
        CancelRequest cancelRequest = new CancelRequest();
        UniqueID uniqueID = new UniqueID();
        uniqueID.setType("501");
        uniqueID.setID(orderEntity.getBuyOrderId());
        List<UniqueID> lstuniqueID = Lists.newArrayList();
        lstuniqueID.add(uniqueID);
        cancelRequest.setUniqueID(lstuniqueID);
        cancelRequest.setVersion(1);
        ctripDtInfo.setICODE(CtripInterface.CancelRQ.getValue());
        ctripDtInfo.setJsonData(JSONObject.toJSONString(cancelRequest));
        String cancelResult = "";
        CancelRQResult cancelRQResult = new CancelRQResult();
        JSONObject cancelRObject = null;
        try {
            cancelResult = CtripClient.excuteReq(ctripDtInfo);
            cancelRObject = JSONObject.parseObject(cancelResult);
            log.info("携程取消订单，携程订单号：{},返回信息：{}", orderEntity.getBuyOrderId(), cancelResult);
            if (cancelResult.contains("INVALID_TOKEN")) {
                // 睡眠2秒后在执行
                Thread.sleep(2000);
                return cancel(orderEntity, userName);
            }
        } catch (Exception ex) {
            cancelRQResult.setMessage("取消失败");
            orderEntity.setBuyStatus(-2);
            cancelRQResult.setResultCode("-200");
            log.error("取消订单失败，订单号：{},错误信息：{}", orderEntity.getOrderCode(), ex.toString());
        }
        if (cancelRObject!=null){
        //取消成功
        if (cancelRObject.getJSONObject("Success") != null) {
            orderEntity.setOrderStatus(-2);
            orderEntity.setBuyStatus(-2);
            cancelRQResult.setMessage("成功");
            cancelRQResult.setResultCode("0");
            cancelRQResult.setOrderId(orderEntity.getOrderCode().toString());
        } else {
            cancelRQResult.setMessage("取消失败");
            orderEntity.setBuyStatus(-2);
            cancelRQResult.setResultCode("-200");
            }
        }
        //更新采购信息
        orderService.updateById(orderEntity);
        cancelRQResult.setOrderId(orderEntity.getId().toString());
        return XmlUtils.toXML(cancelRQResult);
    }

    /**
     * 前端下单
     *
     * @param manuBookRQ
     * @return
     */
    public R ctripManuOrder(ManuBookRQ manuBookRQ) throws InterruptedException {
        R rRresult = null;
        String orderCode = manuBookRQ.getOrderCode().toString();
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectByOrderId(Constant.Channel.Ctrip.getValue(), orderCode);
        if (dtOrderChannelsEntity == null) {
            return R.error("配置错误：请配置店铺对应的携程渠道");
        }
        CtripDtInfo ctripDtInfo = new CtripDtInfo();
        ctripDtInfo.setAID(Integer.valueOf(dtOrderChannelsEntity.getAccessKey()));
        ctripDtInfo.setSID(dtOrderChannelsEntity.getSid());
        ctripDtInfo.setAccess_Token(dtOrderChannelsEntity.getAccessToken());
        ctripDtInfo.setUniqueID(dtOrderChannelsEntity.getUniqueId());
        ctripDtInfo.setRefresh_Token(dtOrderChannelsEntity.getRefreshToken());
        //构造返回
        BookRQResult bookRQResult = new BookRQResult();
        //更新本地订单
        OrderEntity orderEntity = new OrderEntity();
        R r = manuSaveOrder(manuBookRQ, ctripDtInfo);
        System.out.println(r);
        if (r.getCode() == 0) {
            SaveOrderResult saveOrderResult = (SaveOrderResult) r.get("saveOrderResult");
            Integer buyOrderAmt = Integer.valueOf(r.get("buyOrderPrice").toString());
            orderEntity.setBuyOrderPrice(buyOrderAmt);
            if (StringUtils.equals(saveOrderResult.getResponseStatus().getAck().toLowerCase(), "success")) {
                R r1 = commitOrder(saveOrderResult, ctripDtInfo);
                if (r1.getCode() == 0) {
                    orderEntity.setBuyStatus(1);
                    bookRQResult.setMessage("创建订单成功");
                    bookRQResult.setResultCode("0");
                } else if (r1.get("msg").toString().contains("INVALID_TOKEN")){
                    Thread.sleep(2000);
                    return ctripManuOrder(manuBookRQ);
                }else {
                    orderEntity.setBuyStatus(0);
                    bookRQResult.setMessage("创建订单失败"+r1.get("msg").toString());
                    bookRQResult.setResultCode("-9");
                    rRresult = R.error("创建订单失败");
                }
            } else {
                orderEntity.setBuyStatus(0);
                bookRQResult.setMessage("创建订单失败");
                bookRQResult.setResultCode("-9");
                rRresult = R.error("创建订单失败");
            }
        } else if (r.get("msg").toString().contains("INVALID_TOKEN")) {
            Thread.sleep(2000);
            return ctripManuOrder(manuBookRQ);
        } else {
            orderEntity.setBuyStatus(0);
            bookRQResult.setMessage("创建订单失败");
            bookRQResult.setResultCode("-9");
            rRresult = R.error("创建订单失败"+r.get("msg"));
        }
        bookRQResult.setOrderId(manuBookRQ.getId().toString());
        orderEntity.setId(manuBookRQ.getId());
        orderService.updateById(orderEntity);
        return rRresult;
    }
}
